package top.moxingwang.javawork.arithmetic;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created on 2022/11/2.
 * Java 基于LinkedHashMap实现LRU（LRU是Least Recently Used的缩写，即最近最少使用）
 *
 * -[基于Java实现LRU算法](https://blog.csdn.net/qq_27158477/article/details/118574815)
 *
 * @author MoXingwang
 */
public class LRULinkedHashMap<K, V> {
    private int maxCache;
    private Map<K, V> cache;

    public LRULinkedHashMap(int maxCache) {
        this.maxCache = maxCache;
        cache = new LinkedHashMap() {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() >= getMaxCache();
            }
        };
    }

    public V put(K k, V v) {
        return cache.put(k, v);
    }

    public V get(K k) {
        return cache.get(k);
    }


    public int getMaxCache() {
        return maxCache;
    }

    public void setMaxCache(int maxCache) {
        this.maxCache = maxCache;
    }

    public Map<K, V> getCache() {
        return cache;
    }

    public void setCache(Map<K, V> cache) {
        this.cache = cache;
    }
}
